#include "loginhelper.h"
#include <QCryptopp/hex.h>
#include <QCryptopp/sha.h>
#include <QCryptopp/base64.h>
#include <QCryptopp/filters.h>
#include <string>
#include "main.h"
#include "network/tlpacket.h"

USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)

LoginHelper::LoginHelper()
{
}

bool LoginHelper::Login(QString username, QString password)
{
    return false; //database->CheckLogin(username,password);
}

QString LoginHelper::LoginSalt(QString username, QString password)
{
    CryptoPP::SHA256 hash256;
    CryptoPP::SHA512 hash512;
    byte huser[CryptoPP::SHA256::DIGESTSIZE];
    byte hpass[CryptoPP::SHA512::DIGESTSIZE];
    QString salt;
    salt=username+":"+password;
    hash256.CalculateDigest(huser,(const byte *)salt.toAscii().data(),salt.size());
    hash512.CalculateDigest(hpass,(const byte *)salt.toAscii().data(),salt.size());

    QByteArray b64user((char*)huser);
    QByteArray b64pass((char*)hpass);
    QString s64user(b64user.toBase64());
    QString s64pass(b64pass.toBase64());
    QString ret;


    ret.append(s64user.mid(0,20));
    ret.append(' ');
    ret.append(s64pass.mid(0,32));
    _log->LogIt(ret);
    return ret;
}

bool LoginHelper::AddUser(QString username, QString password)
{
    QString fsalt = LoginSalt(username,password);
    QStringList salts = fsalt.split(' ');
    CryptoPP::SHA256 hash256;
    byte huser[CryptoPP::SHA256::DIGESTSIZE];
    QString salt(password);
    salt.append(salts.at(0));
    hash256.CalculateDigest(huser,(const byte *)salt.toAscii().data(),salt.size());
    _log->LogIt(QByteArray((char*)huser,CryptoPP::SHA256::DIGESTSIZE).toHex());
    for(int i=0; i<19;i++)
    {
        QByteArray bhash((char*)huser,CryptoPP::SHA256::DIGESTSIZE);
        QString shash(bhash.toHex());
        hash256.CalculateDigest(huser,(byte*)shash.toAscii().data(),CryptoPP::SHA256::DIGESTSIZE*2);
            _log->LogIt(QByteArray((char*)huser,CryptoPP::SHA256::DIGESTSIZE).toHex());
    }

    QByteArray lastChallenge;
    lastChallenge.append((const char*)huser,CryptoPP::SHA256::DIGESTSIZE);
    lastChallenge.append(salts.at(1));

    hash256.CalculateDigest(huser,(byte*)lastChallenge.data(),lastChallenge.size());
    QByteArray ret((char*)huser,CryptoPP::SHA256::DIGESTSIZE);
    return database->AddUser(username,QString(ret.toHex()),fsalt);
}

